package com.hmall.service;


import com.hdmall.business.common.common.ResponseCode;
import com.hdmall.business.common.common.ServerResponse;
import com.hmall.mapper.BiUserActionHistoryMapper;
import com.hmall.model.BiUserActionHistory;
import com.hmall.model.SysUser;
import com.hdmall.business.common.util.DateTimeUtil;
import com.hdmall.business.common.util.IpUtil;
import com.hdmall.business.common.util.PhoneUtil;
import com.hdmall.business.common.vo.AddressResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 用户行为服务层
 */
@Service
public class BiUserActionHistoryService {
    @Autowired
    private BiUserActionHistoryMapper biUserActionHistoryMapper;

    public ServerResponse insert(HttpServletRequest request, SysUser user,Integer userRoleId,String userRoleName,  String action, String actionUrl, String content){
        BiUserActionHistory actionHistory=new BiUserActionHistory();
        actionHistory.setAction(action);
        actionHistory.setActionUrl(actionUrl);
        actionHistory.setContent(content);

        actionHistory.setUserRoleId(userRoleId);
        actionHistory.setUserRoleName(userRoleName);
        String agent=request.getHeader("user-agent");
        if(agent.toLowerCase().contains("mac")||agent.toLowerCase().contains("ios")){
            actionHistory.setDeviceName("苹果:"+agent.substring(0,agent.indexOf(")")+1));
            actionHistory.setDeviceType(2);
            //deviceVo.setDeviceName("苹果");
        }else if(agent.toLowerCase().contains("android")){
            actionHistory.setDeviceName("安卓:"+agent.substring(0,agent.indexOf(")")));
            actionHistory.setDeviceType(1);
        }else{
            actionHistory.setDeviceType(3);
            actionHistory.setDeviceName("PC:"+agent.substring(0,agent.indexOf(")")));
        }
        System.out.println(agent);
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        actionHistory.setIp(ip);
        AddressResultVo addressResult=IpUtil.getBaiduPosition(ip);
        if ("0".equals(addressResult.getStatus())){//状态0 正常
           String province= addressResult.getContent().getAddress_detail().getProvince();
           String city= addressResult.getContent().getAddress_detail().getCity();
           if(province!=null&&!"".equals(province)){
               actionHistory.setProvince(province);
           }
           if(city!=null&&!"".equals(city)){
               actionHistory.setCity(city);
           }
        }
        if(user!=null){
            actionHistory.setUserId(user.getUserId());
            //看是买方还是卖方

            if(user.getPhone()!=null&&!"".equals(user.getPhone())&& "0".equals(addressResult.getStatus())){
                actionHistory.setPhone(user.getPhone());
                String getZoneResult=PhoneUtil.calcMobileCity(user.getPhone());
                if(getZoneResult!=null&&!"".equals(getZoneResult)){
                   String carrier= getZoneResult.substring(getZoneResult.indexOf("carrier")+"carrier".length()+1,getZoneResult.length()-1);
                   actionHistory.setPhoneProvince(carrier);
                }
            }
        }

        try {
            biUserActionHistoryMapper.insertUserActionHis(actionHistory);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByStatus(ResponseCode.USER_BI_ACT_HIS_FOUND.getCode(),ResponseCode.USER_BI_ACT_HIS_FOUND.getDesc());
        }

        return ServerResponse.createBySuccess("用户历史插入成功");

    }

    public ServerResponse<List> selectThreeMonths(){
        List<BiUserActionHistory> biUserActionHistories;
        try {
            biUserActionHistories= biUserActionHistoryMapper.selectThreeMonths();
        } catch (Exception e) {
            e.printStackTrace();
            return  ServerResponse.createByStatus(211,"用户行为查询错误");
        }
        List<Object> list=new ArrayList<Object>();
        Map<String,Object> idsMap=new HashMap<String,Object>();
        List<Long> Ids=new ArrayList<Long>();

        Map<String,Object> ipMap=new HashMap<String,Object>();
        List<String> ips=new ArrayList<String>();

        Map<String,Object> provincesMap=new HashMap<String,Object>();
        List<String> provinces=new ArrayList<String>();

        Map<String,Object> citysMap=new HashMap<String,Object>();
        List<String> citys=new ArrayList<String>();

        Map<String,Object> userIdsMap=new HashMap<String,Object>();
        List<Integer> userIds=new ArrayList<Integer>();

        Map<String,Object> userRoleNamesMap=new HashMap<String,Object>();
        List<String> userRoleNames=new ArrayList<String>();

        Map<String,Object> deviceTypesMap=new HashMap<String,Object>();
        List<Integer> deviceTypes=new ArrayList<Integer>();

        Map<String,Object> deviceNamesMap=new HashMap<String,Object>();
        List<String> deviceNames=new ArrayList<String>();

        Map<String,Object> phoneProvincesMap=new HashMap<String,Object>();
        List<String> phoneProvinces=new ArrayList<String>();

        Map<String,Object> phonesMap=new HashMap<String,Object>();
        List<String> phones=new ArrayList<String>();

        Map<String,Object> createTimesMap=new HashMap<String,Object>();
        List<String> createTimes=new ArrayList<String>();

        Map<String,Object> actionsMap=new HashMap<String,Object>();
        List<String> actions=new ArrayList<String>();

        Map<String,Object> actionUrlsMap=new HashMap<String,Object>();
        List<String> actionUrls=new ArrayList<String>();

        Map<String,Object> contentsMap=new HashMap<String,Object>();
        List<String> contents=new ArrayList<String>();

        for(BiUserActionHistory biUserActionHistory:biUserActionHistories){

            Ids.add(biUserActionHistory.getActionHisId());
            idsMap.put("Ids",Ids);
            ips.add(biUserActionHistory.getIp());
            ipMap.put("ips",ips);
            provinces.add(biUserActionHistory.getProvince());
            provincesMap.put("provinces",provinces);
            citys.add(biUserActionHistory.getCity());
            citysMap.put("citys",citys);
            userIds.add(biUserActionHistory.getUserId());
            userIdsMap.put("userIds",userIds);
            userRoleNames.add(biUserActionHistory.getUserRoleName());
            userRoleNamesMap.put("userRoleNames",userRoleNames);
            deviceTypes.add(biUserActionHistory.getDeviceType());
            deviceTypesMap.put("deviceTypes",deviceTypes);
            deviceNames.add(biUserActionHistory.getDeviceName());
            deviceNamesMap.put("deviceNames",deviceNames);
            phoneProvinces.add(biUserActionHistory.getProvince());
            phoneProvincesMap.put("phoneProvinces",phoneProvinces);
            phones.add(biUserActionHistory.getPhone());
            phonesMap.put("phones",phones);
            createTimes.add(DateTimeUtil.dateToStr(biUserActionHistory.getCreateTime()));
            createTimesMap.put("createTimes",createTimes);
            actions.add(biUserActionHistory.getAction());
            actionsMap.put("actions",actions);
            actionUrls.add(biUserActionHistory.getActionUrl());
            actionUrlsMap.put("actionUrls",actionUrls);
            contents.add(biUserActionHistory.getContent());
            contentsMap.put("contents",contents);
        }
        list.add(idsMap);
        list.add(ipMap);
        list.add(provincesMap);
        list.add(citysMap);
        list.add(userIdsMap);
        list.add(userRoleNamesMap);
        list.add(deviceTypesMap);
        list.add(deviceNamesMap);
        list.add(phoneProvincesMap);
        list.add(phonesMap);
        list.add(createTimesMap);
        list.add(actionsMap);
        list.add(actionUrlsMap);
        list.add(contentsMap);
        return  ServerResponse.createBySuccess(list);
    }

    public static void main(String[] args) {
       /* String __GetZoneResult_="__GetZoneResult_ = {    mts:'1835891',    province:'浙江',    catName:'中国移动',    telString:'18358912521',\tareaVid:'30510',\tispVid:'3236139',\tcarrier:'浙江移动'}";
        __GetZoneResult_=__GetZoneResult_.substring(__GetZoneResult_.indexOf("carrier")+"carrier".length()+1,__GetZoneResult_.length()-1);
        System.out.println(__GetZoneResult_);*/
    }

}
